package com.yc.chatroom.ui.client.controller;

import java.net.URL;
import java.util.ResourceBundle;

import com.yc.chatroom.client.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.yc.chatroom.client.TestCompan;
import com.yc.chatroom.common.Constant;
import com.yc.chatroom.common.dto.LoginResponse;
import com.yc.chatroom.common.dto.ResultDto;
import com.yc.chatroom.common.util.MD5SignUtil;
import com.yc.chatroom.ui.client.fx.StageManager;
import com.yc.chatroom.ui.client.utils.SpringUtils;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;

@Component
public class LoginController extends BaseController implements Initializable {

	public static LoginController ctrl;
	
	@FXML
	private TextField TextField_userName;
	
	@FXML
	private PasswordField PasswordField_password;
	
	@FXML
	private CheckBox CheckBox_rememberPassword;
	
	@FXML
	private CheckBox CheckBox_autoLogin;
	
	@FXML
	private Button Button_login;
	
	/**
	 * 因为是登录页的标头图片事件，这里如果不注入图片，上面的事件无法触发
	 */
	@FXML
	private ImageView ImageView_title;
	
	private StageManager stageManager;
	
	@Autowired
	private LoginService loginService;
	
	/**
	 * 用于移动窗口
	 */
	private double xOffSet = 0;
	private double yOffSet = 0;
	
	@Override
	public void initialize(URL location, ResourceBundle resources) {
		ctrl = this;
		stageManager = SpringUtils.getBean(StageManager.class);
	}
	
	/**
	 * 登录按钮事件
	 */
	@FXML
	public void LoginButtonAction() {
		System.out.println("---------click");

		//获取用户名输入框内容
		String userName = TextField_userName.getText();
		//获取密码输入框内容
		String password = PasswordField_password.getText();
		System.out.println("userName =" + userName);
		System.out.println("password =" + password);
		//调用client的登录接口
		LoginResponse res = loginService.login(userName, MD5SignUtil.toMd5(password));
		//轮询
		if (Integer.valueOf(Constant.RESULT_CODE_SUCCESS).equals(res.getCode())) {
			//关闭当前页面，弹出首页
			//加载数据
			stageManager.switchChatRoomPage();
		}
	}
	
	/**
	 * 鼠标事件
	 */
	@FXML
	public void mousePressedEvent(MouseEvent event) {
		xOffSet = event.getSceneX();
	    yOffSet = event.getSceneY();
	}
	
	/**
	 * 鼠标事件
	 */
	@FXML
	public void mouseDraggedEvent(MouseEvent event) {
		stageManager.primaryStage.setX(event.getScreenX() - xOffSet);
		stageManager.primaryStage.setY(event.getScreenY() - yOffSet);
	}

}
